package com.example.retrofit.aspect;

import com.example.retrofit.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName WebLogAspect
 * @Deacription web日志切面
 * @Author test
 * @Date 2022/4/8
 * @Version 1.0
 **/
@Aspect
@Component
@Slf4j
public class WebLogAspect {
    /**
     * 以 controller 包下定义的所有请求为切入点
     */
    @Pointcut("execution(public * com.example.retrofit.controller..*.*(..))")
    public void webLog() {
    }

    /**
     * 环绕
     *
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 打印请求 url
        System.out.println("Url:{}" + request.getRequestURI());
        System.out.println("Parameters:{}" + JsonUtil.toString(request.getParameterMap()));
        System.out.println("Class:{}" + proceedingJoinPoint.getSignature().getDeclaringTypeName());
        System.out.println("Method:{}" + proceedingJoinPoint.getSignature().getName());
        System.out.println("Request Args:{}" + JsonUtil.toString(proceedingJoinPoint.getArgs()));
        //时间
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        // 打印出参
        System.out.println("Response:{}" + JsonUtil.toString(result));
        // 执行耗时
        System.out.println("Time-Consuming:{} ms" + (System.currentTimeMillis() - startTime));
        return result;
    }
}
